<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############


class JFX_Data_File
{
	public $meta = array(
		'filepath' => '',
		'module_key' => '',
		'mime' => '',
		'bytes' => '',
		'filename' => '',
		'friendly_name' => '',
		'extension' => '',
		'created' => '',
		'modified' => ''
	);
	public function __construct($filepath, $filename='', $moduleKey=''){
		$this->load($filepath, $filename, $moduleKey);
		$this->meta['created'] = time();
	}

	public function getAbsolutePath(){
		$CONFIG = JFX::registry('config');
		return $CONFIG->dataDir.'/'.$this->meta['module_key'].'/'.$this->meta['filepath'].'/'.$this->meta['filename'];
	}

	public static function makePath($path){
		$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
		$dirs = explode('/', $path);
		$basePath = '';
		foreach($dirs as $dir){
			if(trim($dir)=='') continue;
			if(!is_dir($basePath.'/'.$dir)){
				mkdir($basePath.'/'.$dir);
			}
			$basePath .= '/'.$dir;
		}
	}

	public function load($filepath='', $filename='', $moduleKey=''){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');

		$q = "SELECT * FROM {$CONFIG->dbprefix}data WHERE filepath = '{$filepath}' AND filename = '{$filename}' AND module_key = '{$moduleKey}'";

		$row = $DB->fetchRow($q);

		$this->meta['filepath'] = $filepath;
		$this->meta['filename'] = $filename;
		$this->meta['module_key'] = $moduleKey;

		if(!is_array($row) || count($row)==0){
			return;
		}

		foreach($this->meta as $k=>$v){
			if(array_key_exists($k, $row)){
				$this->meta[$k] = $row[$k];
			}
		}
	}

	public function save(){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$filepath = $DB->escape($this->meta['filepath']);
		$filename = $DB->escape($this->meta['filename']);
		$moduleKey = $DB->escape($this->meta['module_key']);

		$this->meta['modified'] = time();

		if($DB->countRows($CONFIG->dbprefix.'data', "filepath='{$filepath}' AND filename = '{$filename}' AND module_key = '{$moduleKey}'")==0){
			// insert
			$dbParams = $this->meta;
			$DB->insert($CONFIG->dbprefix.'data', $dbParams);
		}else{
			// update
			$dbParams = $this->meta;
			$DB->update($CONFIG->dbprefix.'data', $dbParams, "filepath = '{$filepath}' AND filename = '{$filename}' AND module_key = '{$moduleKey}'");
		}
	}

	public function delete(){
		$DB = JFX::registry('db');
		$CONFIG = JFX::registry('config');
		$filepath = $DB->escape($this->meta['filepath']);
		$filename = $DB->escape($this->meta['filename']);
		$moduleKey = $DB->escape($this->meta['module_key']);

		if(file_exists($this->getAbsolutePath())){
			unlink($this->getAbsolutePath());
		}

		if($DB->countRows($CONFIG->dbprefix.'data', "filepath='{$filepath}' AND filename = '{$filename}' AND module_key = '{$moduleKey}'")>0){
				// delete from db
				$DB->delete($CONFIG->dbprefix.'data', "filepath = '{$filepath}' AND filename = '{$filename}' AND module_key = '{$moduleKey}'");

		}
	}

	public function rename($newName){
		$oldName = $this->meta['filename'];
		$oldPath = $this->getAbsolutePath();
		$this->meta['filename'] = $newName;
		while(file_exists($this->getAbsolutePath())){
			$newNameParts = explode('.', $newName);
			$newNameParts[0] .= '0';
			$newName .= implode('.', $newName);
			$this->meta['filename'] = $newName;
		}
		rename($oldPath, $this->getAbsolutePath());
		$this->save();
		return $newName;
	}

	public function setFile($moduleKey, $filepath, $friendlyName='', $prefix=''){
		$CONFIG = JFX::registry('config');
		$filepaths = explode('/', $filepath);
		$filename = array_pop($filepaths);
		if(!is_dir($CONFIG->dataDir.'/'.$moduleKey)){
			mkdir($CONFIG->dataDir.'/'.$moduleKey);
		}
		$this->meta['module_key'] = $moduleKey;

		$realpath = $CONFIG->dataDir.'/'.$moduleKey.'/'.$filename;
		if($prefix!=''){
			// create directories
			$dirs = explode('/', $prefix);
			$dir = $CONFIG->dataDir.'/'.$moduleKey;
			foreach($dirs as $prefixDir){
				if(!is_dir($dir.'/'.$prefixDir)){
					mkdir($dir.'/'.$prefixDir);
				}
				$dir .= '/'.$prefixDir;
			}
			$realpath = $CONFIG->dataDir.'/'.$moduleKey.'/'.'/'.trim($prefix, '/').'/'.$filename;
		}


		if(file_exists($filepath)){
			copy($filepath, $realpath);
			$this->meta['filepath'] = $prefix;

			// get meta data
			$this->meta['mime'] = mime_content_type($realpath);
			$this->meta['bytes'] = filesize($realpath);
			if($friendlyName==''){
				$friendlyName = $filename;
			}
			$this->meta['friendly_name'] = $friendlyName;
			$this->meta['filename'] = $filename;
			$this->meta['extension'] = array_pop(explode('.', $filename));
			$this->save();
		}
	}

	public function getContents(){
		if(file_exists($this->getAbsolutePath())){
			return file_get_contents($this->getAbsolutePath());
		}else{
			return '';
		}
	}

	public function setContents($contents){
		self::makePath(dirname($this->getAbsolutePath()));
		$fh = fopen($this->getAbsolutePath(), 'w');
		fwrite($fh, $contents);
		fclose($fh);
	}

}






